package mscloud.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.lang.UUID;
import com.elevenms.common.core.constant.RedisConstants;
import com.elevenms.common.core.response.ApiResponse;
import com.elevenms.common.core.response.ApiUtils;
import com.google.code.kaptcha.Producer;
import jakarta.annotation.Resource;
import mscloud.service.CaptchaGenerationStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Datetime: 2025年07月24日09:53
 * @Author: Eleven52AC
 * @Description: 数学验证码生成
 */
@Service
public class MathCaptchaImpl implements CaptchaGenerationStrategy {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducer;


    /**
     *
     * @Author: Eleven52AC
     * @Description: 算术验证码生成
     * @return ApiResponse
     */
    @Override
    public ApiResponse generationCaptchaCode() {
        String captchaKeyUUID = UUID.fastUUID().toString();
        String captchaKey = RedisConstants.CAPTCHA_PREFIX + captchaKeyUUID;
        String fullArithmetic = captchaProducer.createText();
        String operationPart = fullArithmetic.substring(0, fullArithmetic.indexOf("@"));
        String resultPart = fullArithmetic.substring(fullArithmetic.indexOf("@") + 1);
        BufferedImage image = captchaProducer.createImage(operationPart);
        stringRedisTemplate.opsForValue().set(captchaKey, resultPart, RedisConstants.CAPTCHA_EMAIL_TTL, TimeUnit.MINUTES);
        // 转换信息流输出
        FastByteArrayOutputStream out = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", out);
        }catch (IOException e){
            return ApiUtils.error("验证码生成失败",e.getMessage());
        }
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.put("captchaKeyUUID",captchaKeyUUID);
        apiResponse.put("image", Base64.encode(out.toByteArray()));
        return apiResponse;
    }


}
